<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/26
 * Time: 14:40
 */

namespace AdminsBundle\Controller;

use AdminsBundle\Entity\Category as Entity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use AdminsBundle\Helper\MyController;

class CategoryController extends MyController{

    /*快速复制项目通用化配置*/
    private $entity;
    private $entityName = "Category";

    /**
     * @route("Category/add",name="CategoryPreAdd")
     */
    public function add()
    {
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName , $this->entity,   $this->generateUrl($this->entityName."DoAdd"));
        $show = $form->createView();
        $data = array(
            "title" => "新增饰品分类",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Category/add/do",name="CategoryDoAdd")
     *
     * @Method({"GET", "POST"})
     */
    public function doAdd(Request $request)
    {
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName ,  $this->entity);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($this->entity);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreAdd"),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Category/edit/{id}",name="CategoryPreEdit")
     */
    public function edit(Entity $entity)
    {
        $action = $this->generateUrl($this->entityName."DoEdit",array("id"=>$entity->getId()));
        $form = $this->createMyForm($this->entityName ,  $entity ,  $action );
        $show = $form->createView();
        $data = array(
            "title" => "管理饰品分类",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Category/edit/{id}/do",name="CategoryDoEdit")
     *
     * @Method({"GET", "POST"})
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $form = $this->createMyForm($this->entityName ,  $entity );
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreEdit",array("id"=>$entity->getId())),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Category",name="CategoryLists")
     */
    public function lists()
    {
        /*分页配置*/
        if ($page   = $this->getParamRequired("page")){} else { $page = 1;}
        $per_page   = 10;
        $total      = $this->countCond();

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl($this->entityName."Tools"),
            "addUrl"=>$this->generateUrl($this->entityName."PreAdd"),
        );
        $lists = $this->listCond($page,$per_page);

        return $this->render("AdminsBundle:".$this->entityName.":list.php.twig", array(
            'title'     => "饰品分类列表",
            'urls'      => $urls,
            'lists'     => $lists,
            'page'      => $this->creatPage($this->generateUrl($this->entityName."Lists"),$total,$per_page),
        ));
    }

    /**
     * @route("Category/tools",name="CategoryTools")
     */
    public function tools(Request $request)
    {

        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out($this->entityName."Lists","参数丢失");
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out($this->entityName."Lists","参数丢失");
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    $this->entity  = $em->find("AdminsBundle:".$this->entityName,$id);
                    $em->remove($this->entity);
                }
                $em->flush();
            }
        }
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $this->entity  = $em->find("AdminsBundle:".$this->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    $func = "set$key";
                    $this->entity->$func($val);
                }
                $em->persist($this->entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        return $this->redirect($this->generateUrl($this->entityName."Lists")."?".$queryStr);
    }


    private function listCond($page,$per_page)
    {
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder();

        $qb->select(array(
            $this->entityName.".id",
            $this->entityName.".name",
            $this->entityName.".index",))->from("AdminsBundle:".$this->entityName,$this->entityName);
        if ($txtKeywords) {
            $search = $qb->expr()->orX(
                $qb->expr()->like($this->entityName.".name",":key"));
            $qb->where($search)->setParameter("key","%$txtKeywords%");}
        if ($condition = $request->get("cond")) {
            foreach ($condition as $key => $val) {
                if ($val == "") {continue;}
                $qb->andWhere($this->entityName.".$key = :val")
                    ->setParameter("val",$val);}}
        $qb->orderBy($this->entityName.".id","ASC");
        $qb->setFirstResult($page*$per_page - $per_page)->setMaxResults($per_page);
        $results = $qb->getQuery()->getResult();
        return $results;
    }

    private function countCond ()
    {
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder();

        $qb->select(array("COUNT(".$this->entityName.".id) as num"))
            ->from("AdminsBundle:".$this->entityName,$this->entityName);
        if ($txtKeywords) {
            $search = $qb->expr()->orX(
                $qb->expr()->like($this->entityName.".name",":key")
            );
            $qb->where($search)->setParameter("key","%$txtKeywords%");;
        }
        if ($condition = $request->get("cond")) {
            foreach ($condition as $key => $val) {
                if ($val == "") {continue;}
                $qb->andWhere($this->entityName.".$key = :val")
                    ->setParameter("val",$val);
            }
        }
        $result = $qb->getQuery()->getSingleResult();
        return isset($result["num"]) ? $result["num"] : 0 ;
    }
}